var TYPE_DEFAULT_DATA=0;
var TYPE_QUESTION_DATA=1;
var TYPE_ANSWER_DATA=2;
var TYPE_TOPIC_DES=3;

function getQuestionPageList(data, moduleName, containerName, url, type,ajaxSuccessEleFunction) {
	$(function(){
		$.loading("show");
	if (!data) {
		alert("页面异常，请重新操作！");
		return;
	}
	
	var ajaxSuccessEleFun = null;
	
	if(ajaxSuccessEleFunction)ajaxSuccessEleFun=ajaxSuccessEleFunction;
	else{
	switch (type) {
	case TYPE_QUESTION_DATA:
		ajaxSuccessEleFun = ajaxSuccessQuestionEle;
		break;
	case TYPE_ANSWER_DATA:
		ajaxSuccessEleFun = ajaxSuccessAnswerEle;
		break;
	case TYPE_TOPIC_DES:
		ajaxSuccessEleFun = getTopicsDes;
		break;
	default:
		break;
	}
	}//else
	$.ajax({
		timeout:10000,
		type : "get",
		contentType : "application/json;charset=utf-8",
		url :G_BASE_URL+"/"+ url,
		dataType : "json",
		data : data,
		success : function(redata, textStatus) {
			$.loading("hide");
			if(!redata||!redata.rsm)return;
			var getQuestionPageListRev={pageControlId:data.pageControlId,currentPage:redata.currentPage,dataCount:redata.allDataCount,pageSize:redata.pageSize,moduleName:moduleName, containerName:containerName, url:url, type:type};
			getPageData(getQuestionPageListRev);
			var template = $(moduleName).clone();
			//$(containerName).html("");
            if(redata.nextPage)data.nextPage=redata.nextPage;
			$(redata.rsm).each(function(i, domEle) {

				
				template = template.clone();
				ajaxSuccessEleFun(i, domEle,containerName, moduleName, template);

			});

		},

		complete : function(XMLHttpRequest, textStatus) {
			if (uParse) {
				uParse('.markitup-box', {
					rootPath : 'ueditor/'
				});
			}
			// HideLoading();
		},
		error : function() {
			$.loading("hide");
			// 请求出错处理
			alert("请求数据出错，请检查网络或联系管理员！");
		}
	});
}
	)
}

function ajaxSuccessQuestionEle(i, domEle,containerName, moduleName) {
	var template = $(moduleName).clone();
	$(containerName).append(template);
    var questionData=domEle.question;
	var questionHtml = $(moduleName);
	questionHtml.attr("class","aw-item");
	var questionInfoHtml=$(moduleName + " p span");
	var questionUser=$(moduleName + " .aw-user-name img");
	$(moduleName + " .aw-user-name").attr("data-id",questionData.userId);
	$(moduleName + " .aw-user-name").attr("href",G_BASE_URL+userDescUrl+"?uid="+questionData.userId);
	var latestAnswerUser=domEle.latestAnswerUser;
	var title = $(moduleName + " h4 a");
	title.attr("href", "getQuestionById.do?questionId=" + questionData.questionId);
	title.text(questionData.questionName);
    var latestUser=questionHtml.find(".aw-question-content p a");
    questionInfoHtml.html("");
    if(latestAnswerUser!=null&&latestAnswerUser.userId!=null)
    {latestUser.html(latestAnswerUser.nickName);
    latestUser.attr("data-id", latestAnswerUser.userId);
    latestUser.attr("href", G_BASE_URL+userDescUrl+"?uid="+latestAnswerUser.userId);
    questionInfoHtml.html("回复了问题 •");}
    questionUser.attr("src",G_PIC_BASE_URL+domEle.questionUser.photo);

    questionInfoHtml.append(domEle.attentionNum+"人关注 • "+domEle.answerNum+"回复  • "+domEle.lastModifyTime);
    
    
	questionHtml.attr("id", "question" + i);

}

function ajaxSuccessAnswerEle(i, domEle, containerName,moduleName) {
	var template = $(moduleName).clone();
	$(containerName).append(template);
	var questionHtml = $(moduleName);

	var answerText = questionHtml.find("#answer_text");
	var answerUser = questionHtml.find("#answer_user");
	// 回答下面的元素 比如评论，分享等
	var answerFooter = questionHtml.find(".mod-footer");

	var answerJson = domEle.answer;
	var userJson = domEle.userInfo;
	var voteHtml = questionHtml.find(".aw-vote-count");

	var voteData = {
		element : this,
		agree_count : answerJson.voteCount,
		flag : 0,
		user_name : G_USER_ID,
		answer_id : answerJson.answerId
	};
	voteHtml.attr("onclick", "insertVoteBar({element:this,agree_count:"
			+ answerJson.voteCount + ",flag:0,user_name:G_USER_ID,answer_id:"
			+ answerJson.answerId + "})");

	voteHtml.text(answerJson.voteCount);
	answerText.find(".markitup-box").html(answerJson.answerContext);
	answerUser.find(".aw-user-name").text(userJson.userId);
	questionHtml.find(".aw-user-img img").attr("src", "." + userJson.photo);
	answerFooter.find("#answer_time").text(answerJson.createTime);
	questionHtml.attr("id", "answer" + i);
	questionHtml.attr("answer-id", answerJson.answerId);
}
// 开启连接
function start_check_inbox_num() {
	if (!check_user()) {
		return;
	}
	JS.Engine.start(G_BASE_URL+'/conn');
	JS.Engine.on({
		inbox : function(data, timespan, engine) {
			// $('#inbox_unread').html(Number(data.rsm));
			if (data) {
				var inbox_unread_num = Number(data.rsm);
				$('.badge.badge-important').html(inbox_unread_num);
				if (inbox_unread_num > 0) {
					$('.badge.badge-important').css('display', 'inline');
				} else {
					$('.badge.badge-important').css('display', 'none');
				}
			}
		}
//		usernum : function(data,timespan,engine){
//			if(data){
//				var online_user_num = Number(data.rsm.onlineUserNum);
//				var all_user_num = Number(data.rsm.allUserNum);
//			}
//		}
	});
	

}

// 检测是否登陆，登陆显示用户名，未登录显示登陆&注册
function check_login() {
	var template;
	if (!check_user()) {
		// var html = '<span> <a href= ' + G_BASE_URL + '/html/register.html
		// target="_blank">注册</a><a href=' + G_BASE_URL +
		// '/html/signin.html>登录</a></span>';
		template = Hogan.compile(HR_TEMPLATE.login_register).render();
		$(".aw-user-nav").html(template);

	} else {
		
		template = Hogan.compile(HR_TEMPLATE.already_login).render({
			'user_id':G_USER_ID,
			'user_img':G_USER_IMG
		});
		$(".aw-user-nav").html(template);
	}
}

function check_user() {
	if (G_USER_ID == 'null_user') {
		return false;
	}
	return true;
}

function check_admin() {
	if (G_ADMIN_ID == 'null_admin') {
		return false;
	}
	return true;
}
//查询在线用户数目和总注册数
function check_user_num(){
	if(check_user()){
		$.get(G_BASE_URL + "/ajax/getUserNum.do", function(result) {

			if (result.errno != 1) {
				$.alert(result.err);
			} else {
				if (result.rsm) {
					var online_user_num = Number(result.rsm.onlineUserNum);
//					首次登陆显示bug
					if(online_user_num == 0){
						online_user_num = 1;
					}
					var all_user_num = Number(result.rsm.allUserNum);
					var user_num = "在线人数：" + online_user_num + " 注册人数：" + all_user_num;
					$('#user_num').text(user_num);
				}
			}
		});
	}
}

// 获取url中的参数
(function($) {
	$.getUrlParam = function(name) {
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		var r = window.location.search.substr(1).match(reg);
		if (r != null)
			return unescape(r[2]);
		return null;
	}
})(jQuery);

//转换html标签
function html_entity_decode(string, quote_style){
	//  discuss at: http://phpjs.org/functions/html_entity_decode/
	// original by: john (http://www.jd-tech.net)
	//    input by: ger
	//    input by: Ratheous
	//    input by: Nick Kolosov (http://sammy.ru)
	// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// improved by: marc andreu
	//  revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	//  revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// bugfixed by: Onno Marsman
	// bugfixed by: Brett Zamir (http://brett-zamir.me)
	// bugfixed by: Fox
	//  depends on: get_html_translation_table
	//   example 1: html_entity_decode('Kevin &amp; van Zonneveld');
	//   returns 1: 'Kevin & van Zonneveld'
	//   example 2: html_entity_decode('&amp;lt;');
	//   returns 2: '&lt;'

	var hash_map = {}, symbol = '', tmp_str = '', entity = '';
	tmp_str = string.toString();

	if (false === (hash_map = get_html_translation_table('HTML_ENTITIES',
			quote_style))) {
		return false;
	}

	// fix &amp; problem
	// http://phpjs.org/functions/get_html_translation_table:416#comment_97660
	delete (hash_map['&']);
	hash_map['&'] = '&amp;';

	for (symbol in hash_map) {
		entity = hash_map[symbol];
		tmp_str = tmp_str.split(entity).join(symbol);
	}
	tmp_str = tmp_str.split('&#039;').join("'");

	return tmp_str;
}

function get_html_translation_table(table, quote_style) {
	//  discuss at: http://phpjs.org/functions/get_html_translation_table/
	// original by: Philip Peterson
	//  revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// bugfixed by: noname
	// bugfixed by: Alex
	// bugfixed by: Marco
	// bugfixed by: madipta
	// bugfixed by: Brett Zamir (http://brett-zamir.me)
	// bugfixed by: T.Wild
	// improved by: KELAN
	// improved by: Brett Zamir (http://brett-zamir.me)
	//    input by: Frank Forte
	//    input by: Ratheous
	//        note: It has been decided that we're not going to add global
	//        note: dependencies to php.js, meaning the constants are not
	//        note: real constants, but strings instead. Integers are also supported if someone
	//        note: chooses to create the constants themselves.
	//   example 1: get_html_translation_table('HTML_SPECIALCHARS');
	//   returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}

	var entities = {}, hash_map = {}, decimal;
	var constMappingTable = {}, constMappingQuoteStyle = {};
	var useTable = {}, useQuoteStyle = {};

	// Translate arguments
	constMappingTable[0] = 'HTML_SPECIALCHARS';
	constMappingTable[1] = 'HTML_ENTITIES';
	constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
	constMappingQuoteStyle[2] = 'ENT_COMPAT';
	constMappingQuoteStyle[3] = 'ENT_QUOTES';

	useTable = !isNaN(table) ? constMappingTable[table] : table ? table
			.toUpperCase() : 'HTML_SPECIALCHARS';
	useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style]
			: quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';

	if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
		throw new Error('Table: ' + useTable + ' not supported');
		// return false;
	}

	entities['38'] = '&amp;';
	if (useTable === 'HTML_ENTITIES') {
		entities['160'] = '&nbsp;';
		entities['161'] = '&iexcl;';
		entities['162'] = '&cent;';
		entities['163'] = '&pound;';
		entities['164'] = '&curren;';
		entities['165'] = '&yen;';
		entities['166'] = '&brvbar;';
		entities['167'] = '&sect;';
		entities['168'] = '&uml;';
		entities['169'] = '&copy;';
		entities['170'] = '&ordf;';
		entities['171'] = '&laquo;';
		entities['172'] = '&not;';
		entities['173'] = '&shy;';
		entities['174'] = '&reg;';
		entities['175'] = '&macr;';
		entities['176'] = '&deg;';
		entities['177'] = '&plusmn;';
		entities['178'] = '&sup2;';
		entities['179'] = '&sup3;';
		entities['180'] = '&acute;';
		entities['181'] = '&micro;';
		entities['182'] = '&para;';
		entities['183'] = '&middot;';
		entities['184'] = '&cedil;';
		entities['185'] = '&sup1;';
		entities['186'] = '&ordm;';
		entities['187'] = '&raquo;';
		entities['188'] = '&frac14;';
		entities['189'] = '&frac12;';
		entities['190'] = '&frac34;';
		entities['191'] = '&iquest;';
		entities['192'] = '&Agrave;';
		entities['193'] = '&Aacute;';
		entities['194'] = '&Acirc;';
		entities['195'] = '&Atilde;';
		entities['196'] = '&Auml;';
		entities['197'] = '&Aring;';
		entities['198'] = '&AElig;';
		entities['199'] = '&Ccedil;';
		entities['200'] = '&Egrave;';
		entities['201'] = '&Eacute;';
		entities['202'] = '&Ecirc;';
		entities['203'] = '&Euml;';
		entities['204'] = '&Igrave;';
		entities['205'] = '&Iacute;';
		entities['206'] = '&Icirc;';
		entities['207'] = '&Iuml;';
		entities['208'] = '&ETH;';
		entities['209'] = '&Ntilde;';
		entities['210'] = '&Ograve;';
		entities['211'] = '&Oacute;';
		entities['212'] = '&Ocirc;';
		entities['213'] = '&Otilde;';
		entities['214'] = '&Ouml;';
		entities['215'] = '&times;';
		entities['216'] = '&Oslash;';
		entities['217'] = '&Ugrave;';
		entities['218'] = '&Uacute;';
		entities['219'] = '&Ucirc;';
		entities['220'] = '&Uuml;';
		entities['221'] = '&Yacute;';
		entities['222'] = '&THORN;';
		entities['223'] = '&szlig;';
		entities['224'] = '&agrave;';
		entities['225'] = '&aacute;';
		entities['226'] = '&acirc;';
		entities['227'] = '&atilde;';
		entities['228'] = '&auml;';
		entities['229'] = '&aring;';
		entities['230'] = '&aelig;';
		entities['231'] = '&ccedil;';
		entities['232'] = '&egrave;';
		entities['233'] = '&eacute;';
		entities['234'] = '&ecirc;';
		entities['235'] = '&euml;';
		entities['236'] = '&igrave;';
		entities['237'] = '&iacute;';
		entities['238'] = '&icirc;';
		entities['239'] = '&iuml;';
		entities['240'] = '&eth;';
		entities['241'] = '&ntilde;';
		entities['242'] = '&ograve;';
		entities['243'] = '&oacute;';
		entities['244'] = '&ocirc;';
		entities['245'] = '&otilde;';
		entities['246'] = '&ouml;';
		entities['247'] = '&divide;';
		entities['248'] = '&oslash;';
		entities['249'] = '&ugrave;';
		entities['250'] = '&uacute;';
		entities['251'] = '&ucirc;';
		entities['252'] = '&uuml;';
		entities['253'] = '&yacute;';
		entities['254'] = '&thorn;';
		entities['255'] = '&yuml;';
	}

	if (useQuoteStyle !== 'ENT_NOQUOTES') {
		entities['34'] = '&quot;';
	}
	if (useQuoteStyle === 'ENT_QUOTES') {
		entities['39'] = '&#39;';
	}
	entities['60'] = '&lt;';
	entities['62'] = '&gt;';

	// ascii decimals to real symbols
	for (decimal in entities) {
		if (entities.hasOwnProperty(decimal)) {
			hash_map[String.fromCharCode(decimal)] = entities[decimal];
		}
	}

	return hash_map;
}

function getPageData(params){
$(function() {       
	//PageCallback(0);    //Load事件，初始化表格数据，页面索引为0（第一页）
    if(!params.pageControlId||!$(params.pageControlId))  return;                                      
    //分页，PageCount是总条目数，这是必选参数，其它参数都是可选
	if(params&&params.dataCount&&params.pageSize&&params.currentPage&&params.currentPage==1){
    $("#page-control").pagination(params.dataCount, {
        callback: PageCallback,
        prev_text: '上一页',       //上一页按钮里text
        next_text: '下一页',       //下一页按钮里text
        items_per_page: params.pageSize,  //显示条数
        num_display_entries: 6,    //连续分页主体部分分页条目数
        current_page: params.currentPage-1,   //当前页索引 0代表第一页
        num_edge_entries: 2        //两侧首尾分页条目数
    });
	}
    //翻页调用
    function PageCallback(index, jq) {           
        //InitTable(index);
    	params.page=index+1;
    	$(params.containerName).html("")
    	getQuestionPageList(params, params.moduleName, params.containerName, params.url, params.type)
    }
    //请求数据
    function InitTable(pageIndex) {                                
        $.ajax({ 
            type: "POST",
            dataType: "text",
            url: 'Handler/PagerHandler.ashx',      //提交到一般处理程序请求数据
            data: "pageIndex=" + (pageIndex + 1) + "&pageSize=" + pageSize,          //提交两个参数：pageIndex(页面索引)，pageSize(显示条数)                
            success: function(data) {                                 
                $("#Result tr:gt(0)").remove();        //移除Id为Result的表格里的行，从第二行开始（这里根据页面布局不同页变）
                $("#Result").append(data);             //将返回的数据追加到表格
            }
        });            
    }
    
});
}
